package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.PageQuery;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author YUBOY
 * @date 2025/1/12
 * @Description
 */
@RestController
@RequestMapping("/users")
@Api("用户管理")
@RequiredArgsConstructor// 自动注入初始化所含有的变量 自动构造函数
public class UserController {
//    @Autowired 此时可以不用加@Autowired注解
    private final IUserService userService;


    //新增用户
    @PostMapping
    @ApiOperation("新增用户")
    public void saaveUser(@RequestBody UserFormDTO userDTO) {
        System.out.println("新增用户");
        //1.把DTO对象拷贝到PO对象中
        User userPO = new User();
        BeanUtil.copyProperties(userDTO, userPO);
        //2.调用业务层新增用户
        userService.save(userPO);
    }

    //删除用户
    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void deleteUser(@ApiParam("用户id") @PathVariable Long id) {
        userService.removeById(id);
    }
    //根据id查询用户
    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户")
    public UserVO getUserById(@ApiParam("用户id") @PathVariable Long id) {
        return userService.queryUserAndAddress(id);
    }

    /**
     * 根据ids批量查询用户
     * @param ids
     * @return
     */
    @GetMapping()
    @ApiOperation("根据id批量查询用户")
    public List<UserVO> getUserByIds(@RequestParam("ids") List<Long> ids) {
        return userService.listQueryUserAndAddress(ids);
    }

    /**
     * 根据用户id实现扣减账户余额
     */
    @ApiOperation("扣减用户账户余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void deduct(@ApiParam("用户id") @PathVariable("id") Long userId,
                       @ApiParam("扣减金额") @PathVariable("money") Integer money) {
        userService.deductBanlance(userId, money);
    }

    /**
     * 根据复杂条件批量查询用户
     * @param userQuery
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据复杂条件批量查询用户")
    public List<UserVO> getUserByIds(UserQuery userQuery) {
        List<User> users = userService.queryUsers(
                userQuery.getName(), userQuery.getStatus(),
                userQuery.getMinBalance(), userQuery.getMaxBalance());
        return BeanUtil.copyToList(users, UserVO.class);
    }
    @GetMapping("/paqe")
    @ApiOperation("根据复杂条件分页批量查询用户")
    public PageDTO<UserVO> getUserByPages(UserQuery userQuery) {
       return userService.queryUserByPages(userQuery);
    }
}
